package com.calmcar.adas;

import android.app.Application;
import android.os.Environment;

import com.calmcar.adas.conf.Constant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by wwnxiao on 2018/4/12.
 */

public class AdasApp extends Application implements Thread.UncaughtExceptionHandler {
    @Override
    public void onCreate() {
        super.onCreate();
        instance=this;
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

   private static  AdasApp instance;
    public static  AdasApp getInStance(){
        return instance;
    }

    @Override
    public void uncaughtException(Thread t, Throwable ex) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("\r\n\r\n");
        buffer.append(new Date().toString());
        buffer.append("\r\n");
        buffer.append(ex.toString());
        buffer.append("\r\n");
        for (StackTraceElement traceElement : ex.getStackTrace()) {
            buffer.append(traceElement.toString());
            buffer.append("\r\n");
        }
        String logPath = Environment.getExternalStorageDirectory().getPath() + Constant.APP_LOG_PATH;
        File tmpDir = new File(logPath);
        if (!tmpDir.exists()) {
            tmpDir.mkdirs();
        }

        SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String logDate=dateformat.format(new Date());
        File errLog = new File(logPath , logDate+".log");
        try {
            if (!errLog.exists()) {
                errLog.createNewFile();
            }
            OutputStream os = new FileOutputStream(errLog, true);
            os.write(buffer.toString().getBytes( "UTF-8"));
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
